package com.app.framework.socket.codec;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import com.app.framework.socket.Packet;

public class PacketDecoder extends FrameDecoder {

	private final static Logger logger = Logger.getLogger(PacketDecoder.class);
	// 消息长度较大的报警信息
	private final static int LENGTH_WARN = 2048;//TODO 还需要控制每个包的大小
	// 最大消息数
	private final static int MAX_PACKET_NUM = 20;
	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel,
			ChannelBuffer buffer) throws Exception {
		
		List<Packet> lst = new ArrayList<Packet>();
		
		for(int i=0;i<MAX_PACKET_NUM;i++) {
			
			if(buffer.readableBytes() >= 4) {//4是short的length和short的type 占用
				buffer.markReaderIndex();//如果消息体不完整的话 要把readerindex重置到此处
				
				short length = buffer.readShort();//消息体长度
				
				short type = buffer.readShort();//消息类型
				
				if(buffer.readableBytes() >= length) {//消息体
					
					byte[] content = new byte[length];
					if(length > 0) {
						
						buffer.readBytes(content);
					}
					 
					Packet packet = new Packet(type,content);
					
					lst.add(packet);
					if (length >= LENGTH_WARN) {
						logger.warn("packet ["+packet.getType() + "] [decodeMsgTooBig] [" + length + "]");
					}
				}
				else {//消息体不完整,重置到mark处
					buffer.resetReaderIndex();
					break;
				}
			}
			else {
				break;
			}
		}
		
		if(lst.size() > 0) {
			return lst;
		}
		return null;
	}

}
